///////////////////////////////////////////////////////////////////////////////
// TOOLS / ADDINS
///////////////////////////////////////////////////////////////////////////////

#addin nuget:?package=Cake.WebDeploy&version=0.3.4

//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////

var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var verbosity = Argument("verbosity", Verbosity.Minimal);

//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////

var solution = "./WebDeployDemo.sln";

//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////

Task("Clean")
    .ContinueOnError()
    .Does(() =>
{
    CleanDirectories("./artifacts");
    CleanDirectories("./src/*/bin");
    CleanDirectories("./test/*/bin");
});

Task("Build")
    .IsDependentOn("Clean")
    .Does(() =>
{
    var settings = new MSBuildSettings()
    .SetConfiguration(configuration)
    .SetVerbosity(verbosity)
    .WithProperty("DeployOnBuild", "true");
    MSBuild(solution, settings);
});

Task("Zip")
    .IsDependentOn("Build")
    .Does(() =>
{
    CreateDirectory("./artifacts");
    Zip("./WebDeployDemo/bin/Release/Publish", System.IO.Path.GetFullPath("./artifacts/site.zip"));
});

Task("Deploy")
    .IsDependentOn("Zip")
    .Does(() =>
{
    // 机密数据不应存放在脚本中，建议存储到环境变量
    var computerName = EnvironmentVariable("SERVER_ADDRESS");// 例如 120.238.120.238
    var username = EnvironmentVariable("DEPLOY_USERNAME");
    var password = EnvironmentVariable("DEPLOY_PASSWORD");

    DeployWebsite(new DeploySettings()
    {
        SourcePath = System.IO.Path.GetFullPath("./artifacts/site.zip"),
        SiteName = "TestSite",

        ComputerName = computerName,
        Username = username,
        Password = password,
        UseAppOffline = true,// 另外可以参考使用 app_offline.htm 的方式 https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/app-offline?view=aspnetcore-5.0
        Delete = false// true 则会删除zip包中不存在的文件
    });
});

Task("Default")
    .IsDependentOn("Deploy");

//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////

RunTarget(target);